package com.ruicar.afs.cloud.afscase.monitor.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPool;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPoolHistory;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolHistoryService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.common.utils.Const;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.monitor.service.AgingMonitorService;
import com.ruicar.afs.cloud.afscase.monitor.sort.AgingMonitorSort;
import com.ruicar.afs.cloud.afscase.monitor.vo.PersonalMonitorBusinessVO;
import com.ruicar.afs.cloud.afscase.monitor.vo.PersonalMonitorVO;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.entity.CaseConfParam;
import com.ruicar.afs.cloud.afscase.paramconfmanagement.service.CaseConfParamService;
import com.ruicar.afs.cloud.afscase.processor.enums.NormalSubmitType;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.feign.api.RemoteUserService;
import com.ruicar.afs.cloud.common.core.security.dto.UserInfo;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.security.vo.RoleVo;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessTypeEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ProcessTypeEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.WhetherEnum;
import com.ruicar.afs.cloud.seats.condition.SysUserDto;
import com.ruicar.afs.cloud.seats.entity.UserCollocation;
import com.ruicar.afs.cloud.seats.feign.UserDetailsInfoFeign;
import com.ruicar.afs.cloud.seats.service.UserCollocationService;
import com.ruicar.afs.cloud.seats.util.PostStatus;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author Peng Jinbo
 * @Date 2020/09/18 13:31
 */
@Service
@AllArgsConstructor
public class AgingMonitorServiceImpl implements AgingMonitorService {

    private static final List<Function<PersonalMonitorVO,Collection<String>>> GET_COLL_FUNCTION_LIST;

    static{
        // 所有的统计项
        GET_COLL_FUNCTION_LIST = new ArrayList<>();
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTotal);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumWaitCheck);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumWaitCheck);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumReviseReply);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumCheck);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumReject);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumCondition);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumCallback);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumAssertChange);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumFraudInspect);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getNumRepertoryOverdue);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTodayNumReviseParse);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTodayNumAlreadyCheckFinal);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTodayNumAlreadyConditionFinal);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTodayNumAlreadyEnd);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTodayNumAlreadyRejectFinal);
        GET_COLL_FUNCTION_LIST.add(PersonalMonitorVO::getTodayNumProcess);
    }

    private UserCollocationService userCollocationService;

    private WorkTaskPoolService workTaskPoolService;

    private WorkTaskPoolHistoryService workTaskPoolHistoryService;

    private CaseBaseInfoService caseBaseInfoService;

    private UserDetailsInfoFeign userDetailsInfoFeign;

    private CaseConfParamService caseConfParamService;

    private RemoteUserService remoteUserService;

    @Override
    public List leaderMonitor() {
        String currentUserName = SecurityUtils.getUsername();
        // 当前登录人组下所有组员
        List<UserCollocation> leaderMemberList = userCollocationService.list(
                Wrappers.<UserCollocation>lambdaQuery()
                        .eq(UserCollocation::getGroupLeaderLoginName, currentUserName)
        );
        return query(leaderMemberList);
    }

    @Override
    public PersonalMonitorBusinessVO departmentMonitor() {
        CaseConfParam param = caseConfParamService.getOne(
                Wrappers.<CaseConfParam>lambdaQuery()
                        .eq(CaseConfParam::getParamType, Const.PARAMS_TASK_QUERY_DEPARTMENT)
        );
        if (Objects.isNull(param)) {
            throw new AfsBaseException("部门参数不存在，请先维护当前参数");
        }
        IResponse<List<SysUserDto>> response = userDetailsInfoFeign.getUsersByDepartmentId(param.getParamValue());
        if(CommonConstants.SUCCESS.equals(response.getCode()) && CollectionUtil.isNotEmpty(response.getData())) {
            List<String> staffNameList = response.getData().stream().map(SysUserDto::getUsername).collect(Collectors.toList());
            List<UserCollocation> userCollocationList = userCollocationService.list(
                    Wrappers.<UserCollocation>lambdaQuery()
                        .in(UserCollocation::getLoginName,staffNameList)
            );
            List<PersonalMonitorVO> personalMonitorVOList = query(userCollocationList);
            for (PersonalMonitorVO personalMonitorVO : personalMonitorVOList) {
                personalMonitorVO.setJobPosition(getRoles(personalMonitorVO.getLoginName()));
            }
            PersonalMonitorBusinessVO result = group(personalMonitorVOList);
            result.setNewCar(removeWhenAllZero(result.getNewCar()));
            result.setOldCar(removeWhenAllZero(result.getOldCar()));

            result.setNewCar(result.getNewCar().stream().sorted(AgingMonitorSort.COMPARATOR).collect(Collectors.toList()));
            result.setOldCar(result.getOldCar().stream().sorted(AgingMonitorSort.COMPARATOR).collect(Collectors.toList()));
            return result;
        }else{
            throw new AfsBaseException(response.getMsg());
        }
    }


    @Transactional(readOnly = true)
    public List query(List<UserCollocation> leaderMemberList) {
        // key 组员loginName - val 监测统计数据
        Map<String, PersonalMonitorVO> resultMap = new HashMap<>();
        if (CollectionUtil.isEmpty(leaderMemberList)) return Convert.toList(resultMap.values());

        for (UserCollocation leaderMember : leaderMemberList) {
            if (StrUtil.isBlank(leaderMember.getLoginName())) continue;
            PersonalMonitorVO personalMonitor = new PersonalMonitorVO();
            personalMonitor.setLoginName(leaderMember.getLoginName());
            personalMonitor.setRealName(leaderMember.getUserRealName());
            personalMonitor.setPostStatus(PostStatus.YES.getCode().equals(leaderMember.getPostStatus()) ? PostStatus.YES.getDesc() : PostStatus.NO.getDesc());
            resultMap.put(personalMonitor.getLoginName(), personalMonitor);
        }

        if (CollectionUtil.isEmpty(resultMap)) return Convert.toList(resultMap.values());

        // 目前当前登录人下组员的所有审批待办
        List<WorkTaskPool> waitTaskList =  workTaskPoolService.list(
                Wrappers.<WorkTaskPool>lambdaQuery()
                        .in(WorkTaskPool::getApproveStaff, resultMap.keySet())
        );

        for (WorkTaskPool pool : waitTaskList) {
            calTodayNum(resultMap.get(pool.getApproveStaff()), pool);
        }

        // 常规审批待办
        List<WorkTaskPool> normalWaitTaskList = waitTaskList.stream()
                .filter(pool -> StrUtil.equals(pool.getProcessType(),AfsEnumUtil.key(ProcessTypeEnum.GENERA_APPROVE)))
                .collect(Collectors.toList());


        // key 申请编号 - val 员工姓名
        Map<String, String> applyToStaffMap = new HashMap<>();
        for (WorkTaskPool pool : normalWaitTaskList) {
            applyToStaffMap.put(pool.getApplyNo(), pool.getApproveStaff());
        }

        List<CaseBaseInfo> caseBaseInfoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(applyToStaffMap.keySet())) {
            caseBaseInfoList = caseBaseInfoService.list(
                    Wrappers.<CaseBaseInfo>lambdaQuery()
                            .in(CaseBaseInfo::getApplyNo, applyToStaffMap.keySet())
            );
        }

        for (CaseBaseInfo baseInfo : caseBaseInfoList) {
            String staffName = applyToStaffMap.get(baseInfo.getApplyNo());
            PersonalMonitorVO personalMonitorVO = resultMap.get(staffName);
            calNum(personalMonitorVO, baseInfo);
        }

        // 目前所有业务状态处于暂停的案件
        Set<String> parseApplySet = caseBaseInfoService.list(
                Wrappers.<CaseBaseInfo>lambdaQuery()
                        .eq(CaseBaseInfo::getBusinessStateIn, AfsEnumUtil.key(BusinessStateInEnum.PAUSE))
        ).stream().map(CaseBaseInfo::getApplyNo).collect(Collectors.toSet());


        // 今天所有人的已处理待办
        List<WorkTaskPoolHistory> todayDisposeTaskList = workTaskPoolHistoryService.list(
                Wrappers.<WorkTaskPoolHistory>lambdaQuery()
                        .ne(WorkTaskPoolHistory::getApproveSuggest, AfsEnumUtil.key(NormalSubmitType.REFORMIST))
                        .le(WorkTaskPoolHistory::getEndTime, DateUtil.beginOfDay(DateUtil.yesterday()))
                        .in(WorkTaskPoolHistory::getApproveStaff, resultMap.keySet())
        );
        // key 流程类型 + 申请编号 - val 是否有过退回经销商操作
        Map<String, Boolean> processSendDealerMap = new HashMap<>();
        // 每个案件每个人截止目前最后一次的已处理任务
        Map<String, WorkTaskPoolHistory> uniqueTodayDisposeTaskMap = new HashMap<>();
        for (WorkTaskPoolHistory history : todayDisposeTaskList) {
            String key = history.getApplyNo() + "-" + history.getProcessType() + "-" + history.getApproveStaff();
            WorkTaskPoolHistory exists = uniqueTodayDisposeTaskMap.get(key);
            if (uniqueTodayDisposeTaskMap.containsKey(key)
                    && (Objects.nonNull(exists.getEndTime()) && Objects.nonNull(history.getEndTime()))
                    && exists.getEndTime().compareTo(history.getEndTime()) == -1) continue;
            uniqueTodayDisposeTaskMap.put(key, history);
        }

        for (WorkTaskPoolHistory history : uniqueTodayDisposeTaskMap.values()) {
            if (AfsEnumUtil.key(NormalSubmitType.SEND_BACK_TO_DEALER).equals(history.getApproveSuggest())) {
                String sendBackKey = history.getProcessType() + "-" + history.getApplyNo();
                processSendDealerMap.put(sendBackKey, Boolean.TRUE);
            }

            String staffName = history.getApproveStaff();
            PersonalMonitorVO personalMonitorVO = resultMap.get(staffName);

            // 今日修订暂停案件
            String sendBackKey = history.getProcessType() + "-" + history.getApplyNo();
            if (processSendDealerMap.containsKey(sendBackKey)
                    && processSendDealerMap.get(sendBackKey)
                    && parseApplySet.contains(history.getApplyNo())) {
                personalMonitorVO.getTodayNumReviseParse().add(history.getApplyNo());
            }
            // 今日出结果案件
            if (WhetherEnum.YES.getCode().equals(history.getLastNode())) {
                hasDone(personalMonitorVO, history);
            }
            // 今日处理过的特殊流程
            disposed(personalMonitorVO,history);
        }
        List<PersonalMonitorVO> result = (List<PersonalMonitorVO>) Convert.toList(resultMap.values());
        // 检查案件当前是否修订-暂停状态
        Set<String> checkCaseParseApplyNoSet = new HashSet<>();
        for (PersonalMonitorVO personalMonitorVO : result) {
            checkCaseParseApplyNoSet.addAll(personalMonitorVO.getTodayNumReviseParse());
        }
        if(CollectionUtil.isNotEmpty(checkCaseParseApplyNoSet)){

            Map<String,CaseBaseInfo> untilPauseCaseMap = caseBaseInfoService.list(
                    Wrappers.<CaseBaseInfo>lambdaQuery()
                            .in(CaseBaseInfo::getApplyNo,checkCaseParseApplyNoSet)
                            .eq(CaseBaseInfo::getBusinessStateIn,AfsEnumUtil.key(BusinessStateInEnum.REVISE_PARSE))
            ).stream().collect(Collectors.toMap(CaseBaseInfo::getApplyNo,Function.identity()));

            for (PersonalMonitorVO personalMonitorVO : result) {
                personalMonitorVO.setTodayNumReviseParse(
                        new HashSet<>(CollectionUtil.intersection(personalMonitorVO.getTodayNumReviseParse(),untilPauseCaseMap.keySet())));
            }
        }

        List<PersonalMonitorVO> resultList = removeWhenAllZero(result);


        // 已处理=(当天)(修订暂停+已核准+已附条件+已拒绝+((经手)(资产变更+欺诈调查+库存超期+复议)))
        for (PersonalMonitorVO personalMonitorVO : resultList) {
            personalMonitorVO.getTodayNumProcess().addAll(personalMonitorVO.getTodayNumReviseParse());
            personalMonitorVO.getTodayNumProcess().addAll(personalMonitorVO.getTodayNumAlreadyCheckFinal());
            personalMonitorVO.getTodayNumProcess().addAll(personalMonitorVO.getTodayNumAlreadyConditionFinal());
            personalMonitorVO.getTodayNumProcess().addAll(personalMonitorVO.getTodayNumAlreadyRejectFinal());
        }
        return resultList;
    }

    /**
    * @Description 处理过的，经手的特殊流程
     * 1. 资产变更流程
     * 2. 欺诈调查流程
     * 3. 库存超期
     * 4. 复议
    * @Author Peng_Jinbo
    * @Date 2020/9/22 18:19
    */
    private void disposed(PersonalMonitorVO personalMonitorVO,WorkTaskPoolHistory history){
        if(StrUtil.isBlank(history.getProcessType())) return;
        ProcessTypeEnum processTypeEnum = (ProcessTypeEnum) AfsEnumUtil.getEnum(history.getProcessType(),ProcessTypeEnum.class);
        if(Objects.nonNull(processTypeEnum)){
            Set<ProcessTypeEnum> processTypeSet = new HashSet<>();
            processTypeSet.add(ProcessTypeEnum.FORMAL_REVIEW);
            processTypeSet.add(ProcessTypeEnum.CHANGE_ASSETS);
            processTypeSet.add(ProcessTypeEnum.INVENTORIES_ARE);
            processTypeSet.add(ProcessTypeEnum.SECONDARY_FRAUD);
            if(processTypeSet.contains(processTypeEnum)){
                personalMonitorVO.getTodayNumProcess().add(history.getApplyNo());
            }
        }
    }

    /**
    * @Description 统计项均为 0 时去除当前统计项
    * @Author Peng_Jinbo
    * @Date 2020/9/22 18:26
    */
    private List removeWhenAllZero(List<PersonalMonitorVO> resultList) {
        return resultList.stream()
                .filter(monitor -> {
                    long emptySize = GET_COLL_FUNCTION_LIST.stream()
                            .filter(fun -> CollectionUtil.isEmpty(fun.apply(monitor)))
                            .count();
                    return emptySize != GET_COLL_FUNCTION_LIST.size();
                }).collect(Collectors.toList());
    }


    /**
    * @Description 出结果
    * @Author Peng_Jinbo
    * @Date 2020/9/21 19:25
    */
    private void hasDone(PersonalMonitorVO personalMonitorVO,WorkTaskPoolHistory history){
        if(StrUtil.isBlank(history.getApproveSuggest())
            || !StrUtil.equals(AfsEnumUtil.key(ProcessTypeEnum.FORMAL_REVIEW),history.getProcessType())) return;
        NormalSubmitType submitType = (NormalSubmitType) AfsEnumUtil.getEnum(history.getApproveSuggest(),NormalSubmitType.class);
        HashSet<NormalSubmitType> submitEndTypeSet = new HashSet<>();
        submitEndTypeSet.add(NormalSubmitType.SUGGEST_REJECT_FINAL);
        submitEndTypeSet.add(NormalSubmitType.SUGGEST_CHECK_FINAL);
        submitEndTypeSet.add(NormalSubmitType.SUGGEST_CONDITION_FINAL);
        switch (submitType){
            case SUGGEST_CHECK_FINAL:
                personalMonitorVO.getTodayNumAlreadyCheckFinal().add(history.getApplyNo());
                break;
            case SUGGEST_REJECT_FINAL:
                personalMonitorVO.getTodayNumAlreadyRejectFinal().add(history.getApplyNo());
                break;
            case SUGGEST_CONDITION_FINAL:
                personalMonitorVO.getTodayNumAlreadyConditionFinal().add(history.getApplyNo());
                break;
        }
        if(submitEndTypeSet.contains(submitType)){
            personalMonitorVO.getTodayNumAlreadyEnd().add(history.getApplyNo());
        }
    }


    /**
    * @Description 当日
    * @Author Peng_Jinbo
    * @Date 2020/9/21 19:14
    */
    private void calTodayNum(PersonalMonitorVO personalMonitorVO, WorkTaskPool pool){
        ProcessTypeEnum processTypeEnum = (ProcessTypeEnum) AfsEnumUtil.getEnum(pool.getProcessType(),ProcessTypeEnum.class);
        if(Objects.nonNull(processTypeEnum)){
            switch (processTypeEnum){
                case CHANGE_ASSETS:
                    personalMonitorVO.getNumAssertChange().add(pool.getApplyNo());
                    break;

                case FORMAL_REVIEW:
                    personalMonitorVO.getNumReview().add(pool.getApplyNo());
                    break;

                case SECONDARY_FRAUD:
                    personalMonitorVO.getNumFraudInspect().add(pool.getApplyNo());
                    break;

                case INVENTORIES_ARE:
                    personalMonitorVO.getNumRepertoryOverdue().add(pool.getApplyNo());
                    break;
            }
        }
    }

    /**
    * @Description 截止当前
    * @Author Peng_Jinbo
    * @Date 2020/9/21 19:14
    */
    private void calNum(PersonalMonitorVO personalMonitor, CaseBaseInfo baseInfo){
        BusinessStateInEnum businessStatusInEnum = (BusinessStateInEnum) AfsEnumUtil.getEnum(baseInfo.getBusinessStateIn(),BusinessStateInEnum.class);
        if(Objects.nonNull(businessStatusInEnum)){
            switch (businessStatusInEnum){
                case WAIT_CHECK:
                    personalMonitor.getNumWaitCheck().add(baseInfo.getApplyNo());
                    break;

                case PAUSE:
                    personalMonitor.getNumParse().add(baseInfo.getApplyNo());
                    break;

                case REVISE_REPLY:
                    personalMonitor.getNumReviseReply().add(baseInfo.getApplyNo());
                    break;

                case ADVICE_APPROVED:
                    personalMonitor.getNumCheck().add(baseInfo.getApplyNo());
                    break;

                case ADVICE_REJECT:
                    personalMonitor.getNumReject().add(baseInfo.getApplyNo());
                    break;

                case ADVICE_CONDITIONAL:
                    personalMonitor.getNumCondition().add(baseInfo.getApplyNo());
                    break;

                case REVOCATION:
                    personalMonitor.getNumCallback().add(baseInfo.getApplyNo());
                    break;
            }
            personalMonitor.getTotal().add(baseInfo.getApplyNo());
        }
    }

    /**
    * @Description 根据业务类型分组
    * @Author Peng_Jinbo
    * @Date 2020/9/22 21:43
    */
    private PersonalMonitorBusinessVO group(List<PersonalMonitorVO> monitorList){
        PersonalMonitorBusinessVO group = new PersonalMonitorBusinessVO();
        if(CollectionUtil.isEmpty(monitorList)){
            return group;
        }
        Set<String> applyNoSet = new HashSet<>();
        for (PersonalMonitorVO personalMonitorVO : monitorList) {
            applyNoSet.addAll(getApplyNoSet(personalMonitorVO));
        }
        List<CaseBaseInfo> allCase = caseBaseInfoService.list(
                Wrappers.<CaseBaseInfo>lambdaQuery()
                    .in(CaseBaseInfo::getApplyNo,applyNoSet)
        );
        // 案件申请编号标记
        Map<String,String> businessTypeCaseGroup = allCase.stream().collect(Collectors.toMap(CaseBaseInfo::getApplyNo,CaseBaseInfo::getBusinessType));

        for (PersonalMonitorVO personalMonitorVO : monitorList) {
            PersonalMonitorVO newCarMonitor = new PersonalMonitorVO(personalMonitorVO);
            newCarMonitor.setBusinessType(BusinessTypeEnum.NEW_CAR.getDesc());
            PersonalMonitorVO oldCarMonitor = new PersonalMonitorVO(personalMonitorVO);
            oldCarMonitor.setBusinessType(BusinessTypeEnum.OLD_CAR.getDesc());

            // 根据业务类型分组
            groupBusinessSet(personalMonitorVO,newCarMonitor,oldCarMonitor,businessTypeCaseGroup);
            group.getNewCar().add(newCarMonitor);
            group.getOldCar().add(oldCarMonitor);
        }
        return group;
    }

    /**
    * @Description 获取当前人员监控数据下所有申请编号
    * @Author Peng_Jinbo
    * @Date 2020/9/22 21:44
    */
    private Set<String> getApplyNoSet(PersonalMonitorVO personalMonitorVO){
        Set<String> applyNoSet = new HashSet<>();
        GET_COLL_FUNCTION_LIST.stream().forEach(fun -> applyNoSet.addAll(fun.apply(personalMonitorVO)));
        return applyNoSet;
    }

    private String getRoles(String loginName) {
        IResponse<UserInfo> response = remoteUserService.info(loginName);
        if(CommonConstants.SUCCESS.equals(response.getCode()) && Objects.nonNull(response.getData())){
            UserInfo userInfo = response.getData();
            return CollectionUtil.isNotEmpty(userInfo.getRoleList())
                    ? CollectionUtil.join(userInfo.getRoleList().stream().map(RoleVo::getRoleName).collect(Collectors.toList()), AgingMonitorSort.ROLE_SEPARATOR)
                    : "";
        }else{
            throw new AfsBaseException(response.getMsg());
        }
    }

    /**
    * @Description 根据业务类型，各项数据分组
    * @Author Peng_Jinbo
    * @Date 2020/10/14 11:38
    */
    private void groupBusinessSet(PersonalMonitorVO all,
                     PersonalMonitorVO newCar,
                     PersonalMonitorVO oldCar,
                     Map<String,String> businessGroupMap) {

        GET_COLL_FUNCTION_LIST.stream()
                .forEach(getFun ->
                    getFun.apply(all).stream()
                            .collect(Collectors.groupingBy(businessGroupMap::get))
                            .entrySet()
                            .stream()
                            .forEach(
                                    entry -> {
                                        BusinessTypeEnum businessTypeEnum = (BusinessTypeEnum) AfsEnumUtil.getEnum(entry.getKey(), BusinessTypeEnum.class);
                                        if(businessTypeEnum == BusinessTypeEnum.NEW_CAR){
                                            getFun.apply(newCar).addAll(entry.getValue());
                                        }else if(businessTypeEnum == BusinessTypeEnum.OLD_CAR){
                                            getFun.apply(oldCar).addAll(entry.getValue());
                                        }
                                    }
                            )
                );
    }

}
